package com.su.lightthings.bluetooth

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import com.jieli.jl_bt_ota.util.BluetoothUtil
import com.su.lightthings.bluetooth.BluetoothHelper
import com.su.lightthings.utils.OtaConstant
import com.su.lightthings.viewmodel.CommonViewModel
import java.util.UUID


object BtUtil {

    private const val TAG = "BtUtil"

    /**
     * 蓝牙是否打开
     */
    fun isBleEnable(): Boolean = BluetoothUtil.isBluetoothEnable()

    /**
     * 开始扫描
     */
    fun startScan() {
        BluetoothHelper.getInstance().startScan(OtaConstant.SCAN_TIMEOUT)
    }

    /**
     * 停止扫描
     */
    fun stopScan() {
        BluetoothHelper.getInstance().stopScan()
    }

    /**
     * 连接设备：通过BLE设备进行连接
     * @param device BLE设备
     */
    fun connectBle(device: BluetoothDevice) {
        BluetoothHelper.getInstance().connectDevice(device)
    }

    /**
     * 断开连接
     */
    fun disconnect(device: BluetoothDevice) {
        BluetoothHelper.getInstance().disconnectDevice(device)
    }

    /**
     * 发起绑定ble设备
     * Android原生方法
     * @param address 要绑定的ble设备地址
     */
    fun bondDevice(mBtAdapter: BluetoothAdapter, address: String): Boolean? {
        val bondDevices = mBtAdapter.getRemoteDevice(address)
        val b = bondDevices?.createBond()
        Log.d(TAG, "绑定结果: $b")
        return b
    }

    /**
     * 发送数据
     */
    fun write(
        device: BluetoothDevice,
        data: ByteArray,
    ): Boolean {
        return BluetoothHelper.getInstance().writeDataToDevice(device, data)
    }

    /**
     * 发送数据
     */
    fun write(
        device: BluetoothDevice,
        serviceUUID: UUID,
        characteristicUUID: UUID,
        data: ByteArray,
    ): Boolean {
        return BluetoothHelper.getInstance()
            .writeDataToDevice(device, serviceUUID, characteristicUUID, data)
    }

    fun disableBLEDeviceNotification(type: Int) {
        when (type) {
            0 -> BluetoothHelper.getInstance().disableNormalBLEDeviceNotification()
            1 -> BluetoothHelper.getInstance().disableJlBLEDeviceNotification()
        }
    }

    fun enableBLEDeviceNotification(type: Int) {
        when (type) {
            0 -> BluetoothHelper.getInstance().enableNormalBLEDeviceNotification()
            1 -> BluetoothHelper.getInstance().enableJlBLEDeviceNotification()
        }
    }

    /**
     * 创建常规写入数据
     * @param currFrame 当前帧
     * @param totalFrame 总帧数
     * @param functionId 功能码
     * @param data 数据
     */
    fun makeWriteData(
        currFrame: Int = 1,
        totalFrame: Int = 1,
        functionId: Int,
        data: ByteArray = byteArrayOf()
    ): ByteArray {

        val length = data.size
        var checkSum: UInt =
            (functionId shr 8).toUByte() + functionId.toUByte() + (length shr 8).toUByte() + length.toUByte()

        for (d in data) {
            checkSum += d.toUByte()
        }
        val packageLength = 2 + 2 + length

        val writeData = byteArrayOf(
            0x54,
            0x59,
            currFrame.toByte(),
            totalFrame.toByte(),
            0x00,
//            0x80.toByte(),
            (checkSum shr 8).toByte(),
            checkSum.toByte(),
            (packageLength shr 8).toByte(),
            packageLength.toByte(),
            (functionId shr 8).toByte(),
            functionId.toByte(),
            (length shr 8).toByte(),
            length.toByte(),

            )

        return writeData.plus(data)
    }

    val mBleReceiver by lazy {
        BleReceiver()
    }

    fun registerBtStateBroadcast(context: Context) {
        val filter = IntentFilter()
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        context.registerReceiver(mBleReceiver, filter)
    }

    fun unRegisterBtStateBroadcast(context: Context) {
        context.unregisterReceiver(mBleReceiver)
    }

    class BleReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (BluetoothAdapter.ACTION_STATE_CHANGED == intent.action) {
                val status = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)
                if (status == BluetoothAdapter.STATE_ON) {
                    CommonViewModel.INSTANCE.btState.postValue(true)
                } else if (status == BluetoothAdapter.STATE_OFF) {
                    CommonViewModel.INSTANCE.btState.postValue(false)
                }
            }
        }
    }

}